package com.qiangesoft.sms.aliyun.handler;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.qiangesoft.sms.aliyun.config.AliyunSmsProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Map;

/**
 * 阿里云短信处理器
 *
 * @author qiangesoft
 * @date 2023-05-16
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AliyunSendHandler implements SendHandler {

    private final IAcsClient acsClient;

    private final AliyunSmsProperties aliyunSmsProperties;

    @Override
    public boolean send(Collection<String> phones, Map<String, Object> param) {
        return this.send(phones, aliyunSmsProperties.getTemplateCode(), param);
    }

    @Override
    public boolean send(Collection<String> phones, String templateCode, Map<String, Object> param) {
        SendSmsRequest request = new SendSmsRequest();
        request.setSysMethod(MethodType.POST);
        request.setPhoneNumbers(StringUtils.join(phones, ","));
        request.setSignName(aliyunSmsProperties.getSignName());
        request.setTemplateCode(aliyunSmsProperties.getTemplateCode());
        request.setTemplateParam(JSONObject.toJSONString(param));

        try {
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if ("OK".equals(sendSmsResponse.getCode())) {
                return true;
            }

            log.debug("send fail[code={}, message={}]", sendSmsResponse.getCode(), sendSmsResponse.getMessage());

        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
        return false;
    }

}
